package middlewares

import (
	"gitee.com/go-course/go11/vblog/apps/user"
	"gitee.com/go-course/go11/vblog/common"
	"gitee.com/go-course/go11/vblog/ioc"
	"gitee.com/go-course/go11/vblog/logger"
	"github.com/gin-gonic/gin"
)

func Auth(c *gin.Context) {
	// 写我们的任务逻辑

	logger.L().Debug().Msg("auth ...")

	// 1. 获取Token时(Cookie)
	tk, err := c.Cookie(user.AUTH_COOKIE_NAME)
	if err != nil {
		common.SendFaild(c, err)
		return
	}

	// 检查tk有无
	if tk == "" {
		common.SendFaild(c, common.NewUnauthorized())
		return
	}

	// 2. 调用user ValidateToken 校验Token合法性
	usvc := ioc.GetController(user.AppName).(user.Service)
	tkObj, err := usvc.ValiateToken(c.Request.Context(), user.NewValiateTokenRequest(tk))
	if err != nil {
		common.SendFaild(c, err)
		return
	}

	// 3. 把User对象 放到Ctx中(请求的上下文), 后面CreateBlog需要从上下文中获取用户的身份信息
	c.Set(user.REQUEST_CTX_TOKEN_KEY, tkObj)
}
